<template>
    <div class="video-body">
        <div class="upload-demo">
 <el-upload
    action="/api/file/upload"
     list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-success="videoSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <el-icon><Plus /></el-icon>
    <template #tip>
      <div class="el-upload__tip">
        支持JPG、JPEG、PNG、GIF、BMP、WEBM格式的图片，且大小不能超过10MB
      </div>
    </template>
  </el-upload>
        </div>


  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
  <elform>
    <el-form-item label="标题">
      <el-input placeholder="请输入标题" v-model="postInfo.title"></el-input>
    </el-form-item>
        <el-form-item label="内容">
      <el-input placeholder="请输入内容" v-model="postInfo.content"></el-input>
    </el-form-item>
        <el-form-item>
      <el-button type="primary" @click="submit()">发布</el-button>
    </el-form-item>
  </elform>
    </div>
</template>
<script setup lang="ts">
import {ref,onMounted} from 'vue'
import { useRouter } from 'vue-router';
import useCounter from '@/stores/pinia';
import { addPostAPI } from '../../../api/community';
import {deleteFileAPI} from '../../../api/common'
import { UploadFilled,Plus } from '@element-plus/icons-vue'
import { parseJwt } from '@/stores/pinia';
import { type UploadProps,type FormInstance,type FormRules,type ElMessageBox,type UploadUserFile, ElMessage, UploadInstance, UploadRawFile, genFileId} from 'element-plus'

const menu=ref(0)
const imgUrl=ref()
const router=useRouter()
const counterStore=useCounter()
const disabledVideo=ref(false)
const showVideo=ref(true)
const dialogVisible = ref(false)
const user=ref()
const dialogImageUrl = ref('')
const postInfo=ref({
  authorId:'',
  authorName:'',
  authorAvatar:'',
  title:'',
  content:'',
  imgUrl:[],
  postType:1
})
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  console.log("预览图片地址",dialogImageUrl.value)
  dialogVisible.value = true
}

const menuId=(id: number)=>{
  menu.value=id
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  postInfo.value.imgUrl.pop(uploadFile)
}
const videoSuccess: UploadProps['onSuccess'] = (
  response,//后端存到oss返回的url
  uploadFile//临时的url
) => {
  // form.value.imageUrl = URL.createObjectURL(uploadFile.raw!)
  // form.value.imageUrl = response.data;
  console.log(response.data)
  postInfo.value.imgUrl.push(response.data)
  console.log(postInfo.value.imgUrl)
}
const submit=async()=>{
  if(postInfo.value.title==''||postInfo.value.content==''||postInfo.value.imgUrl==''){
    ElMessage.error('请填写完整信息')
  }else{
        const str=JSON.stringify(postInfo.value.imgUrl)
    postInfo.value.imgUrl=str
    console.log(postInfo.value)
    const result=await addPostAPI(postInfo.value)
    if(result.data.code!=200){
      ElMessage.error('发布失败')
    }else{
    ElMessage.success('发布成功')
    router.push('/community/faxian')
    }
  }
}
const handleProgress=(event: { percent: any; })=>{
  event.percent=50
  console.log(event.percent)
}

const uploadVideo = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = async(files) => {
  // console.log(imgUrl.value)
  await deleteFileAPI(postInfo.value.imgUrl)
  uploadVideo.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadVideo.value!.handleStart(file)
  uploadVideo.value!.submit()
}
onMounted(()=>{
  if(counterStore.jwt){
    user.value=parseJwt(counterStore.jwt)
    postInfo.value.authorAvatar=user.value.imageUrl
    postInfo.value.authorId=user.value.id
    postInfo.value.authorName=user.value.name
    console.log("用户信息",user.value)
  }else{
    router.push('/')
  }
})
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  showVideo.value=false
  // 检查文件类型是否为图片
  const imageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp']
  if (!imageTypes.includes(rawFile.type)) {
    ElMessage.error('只能上传图片格式的文件!')
    return false
  }
  // 检查文件大小（10MB）
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }
  return true
}
</script>
<style scoped>
.video-body{
  position: relative;
  width: 100%;
  height: auto;
  background-color: rgba(252, 252, 252, 0.829);
}
.upload-demo{
  /* width:calc(100% - 40px); */
  /* height: 50%; */
  margin-bottom: 20px;
  /* background-color: #acacac; */
  /* margin:20px */
}
:deep(.el-upload-dragger){
  position: relative;
  width: 100%;
  height: 300px;
  /* padding: 11% 0; */
  background-color: rgba(197, 197, 197, 0.267);
}
</style>